/* ============================ 组件响应 ============================*/
@use "responsive-config" as res-cfg;

/* 自动生成所有响应式规则 */
@mixin generate-responsive-styles {
  // 1. 收集所有断点的样式
  $merged-breakpoints: ();

  @each $component, $settings in res-cfg.$component-profiles {
    $selector: map-get($settings, 'selector');
    $breakpoints: map-get($settings, 'breakpoints');
    $properties: map-get($settings, 'properties');

    // 解析断点引用
    $resolved-breakpoints: if(
      type-of($breakpoints) == 'string',
      map-get(map-get(res-cfg.$component-profiles, $breakpoints), 'breakpoints'),
      $breakpoints
    );

    @for $i from 1 through length($resolved-breakpoints) {
      $bp-name: nth($resolved-breakpoints, $i);
      $bp-config: map-get(res-cfg.$breakpoint-presets, $bp-name);

      // 生成媒体查询条件
      $query: '';
      @if map-has-key($bp-config, 'min-width') and map-has-key($bp-config, 'max-width') {
        $query: '(min-width: #{map-get($bp-config, 'min-width')}) and (max-width: #{map-get($bp-config, 'max-width')})';
      } @else if map-has-key($bp-config, 'max-width') {
        $query: '(max-width: #{map-get($bp-config, 'max-width')})';
      } @else {
        $query: '(min-width: #{map-get($bp-config, 'min-width')})';
      }

      // 按断点合并样式
      $current-breakpoint: if(map-has-key($merged-breakpoints, $query),
                              map-get($merged-breakpoints, $query),
                              ());
      @each $prop, $values in $properties {
        // 当索引越界时使用最后一个值
        $value: if($i <= length($values), nth($values, $i), nth($values, -1));

        $current-breakpoint: map-merge($current-breakpoint, (
          $selector: map-merge(
            map-get($current-breakpoint, $selector) or (),
            (#{$prop}: $value)
          )
        ));
      }
      $merged-breakpoints: map-merge($merged-breakpoints, ($query: $current-breakpoint));
    }
  }

  // 2. 按断点输出合并后的样式
  @each $query, $styles in $merged-breakpoints {
    @media #{$query} {
      @each $selector, $props in $styles {
        #{$selector} {
          @each $prop, $value in $props {
            #{$prop}: #{$value};
          }
        }
      }
    }
  }
}
